<?php

namespace App\Http\Controllers\Api;

use App\Http\Requests\Api\UserRequest;
use App\Models\AppVersion;
use App\Models\Good;
use App\Models\Order;
use App\Models\OrderGood;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;

class UserController extends Controller
{

    public function getToken(Request $request){

//        $data = '{"appid":"wx852b431901245928","bank_type":"OTHERS","cash_fee":"70","fee_type":"CNY","is_subscribe":"N","mch_id":"1507346331","nonce_str":"61de426f9b180","openid":"oIyWn4vTSbMWrvVe9y7tSzTniiQc","out_trade_no":"2022011210523127507","result_code":"SUCCESS","return_code":"SUCCESS","sign":"2A582CA683D03504EA534EB6C29B20CE","time_end":"20220112105237","total_fee":"70","trade_type":"JSAPI","transaction_id":"4200001372202201128359128669"}';
//        $data = json_decode($data,true);
//        update_pay_status($data);
//        dd($data);
//
//        $wechatPay = new WechatPayController();
//
//        $result = $wechatPay->toBalance(1,'oIyWn4vTSbMWrvVe9y7tSzTniiQc');
//        dd($result);
//       $wechat = new WechatController();
//       dd($wechat->send_msg(17));
//        $user = Auth::guard('api')->user();
//        return $this->success($user);
        $token = Auth::guard('api')->attempt(['openid'=>'123456','password'=>'123456']);

        return $this->success('bearer '.$token);
    }
    //解密获取用户手机号
    public function getPhone(Request $request){
        $encryptedData = $request->encryptedData; //加密数据
        $iv = $request->iv; //偏移量
        $sessionKey = $request->sessionKey; // sessionkey
        $openid = $request->openid; //用户openid


        if (!$encryptedData || !$iv || !$sessionKey) {
            $this->failed('参数不全');
        }

        $wechat = new WechatController();

        $res = $wechat->encryptor($sessionKey,$iv,$encryptedData);

        if($res && $res['phoneNumber']){

            $user=Auth::guard('api')->user();
            $user->mobile = $res['phoneNumber'];
            $user->save();

            return $this->success($user);
        }

        return $this->failed('获取失败');
    }


    //  保存昵称头像
    public function saveNickname(Request $request){

        $nickname = $request->nickname;
        $avatarUrl = $request->avatarUrl;

        if(!$nickname || !$avatarUrl){
            return $this->failed('参数不全');
        }
        //$res = $user->update(['header_img'=>$avatarUrl,'nickname'=>$nickname]);
        $user=Auth::guard('api')->user();
        $user->nickname = $nickname;
        $user->header_img = $avatarUrl;

        $user->save();
        return $this->setStatusCode(200)->success($user);

    }


    //根据用户openid获取用户信息
    public function getInfoFromOpenid(Request $request){
        $openid = $request->openid;

        $user = User::where('openid',$openid)->first();

        if(!$user){

            $user = new User();
            $user->openid = $openid;
            $user->password = $openid;
            $user->save();

        }

        $token=Auth::guard('api')->attempt(['openid'=>$openid,'password'=>$openid]);

        $user->token = 'bearer '.$token;


        return $this->success($user);

    }


    //获取商品分类
    public function getType(Request $request){
        $type = $request->type?:2;
        return $this->success(DB::table('type')->where('type',$type)->pluck('name','id'));
    }

    //首页获取用户商品列表

    public function getGoodList(Request $request){

        $user = Auth::guard('api')->user();
        $type = $request->type; //1开蚌  2饰品
        $cate = $request->cate; //饰品分类
        $keywords = $request->keywords; //搜索

        $where = function($query) use ($request){

            if($request->type){
                $query->where('cate',$request->type);
            }
            if($request->cate){ //饰品分类
                $query->where('type_id',$request->cate);
            }

            if($request->keywords){
                $query->where(function ($query) use ($request){
                    $query->Where('name', 'like', '%'.$request->keywords.'%')->orWhere('No', 'like', '%'.$request->keywords.'%');
                });

            }

            $query->where('status',1);
        };


        $goods_list = Good::with(["color:id,color","material:id,material"])
            ->where($where)
//            ->when($keywords,function($query) use ($keywords){
//                $query->where(function ($query) use ($keywords){
//                    return $query->whereHas('user', function ($query) use ($keywords) {
//                        return $query->where('mobile', 'like', '%'.$keywords.'%');
//                    })->orWhereHas('activity',function ($query) use ($keywords){
//                        return $query->Where('title', 'like', '%'.$keywords.'%');
//                    });
//                });
//
//            })
            ->select(['id','color_id','material_id','name','img','old_price','No','new_price','stock'])->get();//获取商品列表

        foreach ($goods_list as $k=>$v){

            $goods_list[$k]->thumb_img =$v->img[0];
            if($v->material){
                $goods_list[$k]->str = $v->color->color."-". $v->material->material;
            }else{
                $goods_list[$k]->str = "";
            }


        }


        return $this->success($goods_list);

    }

    public function getGoodList1(Request $request){

        $user = Auth::guard('api')->user();
        $type = $request->type; //1开蚌  2饰品 3成品
        $cate = $request->cate; //饰品分类
        $keywords = $request->keywords; //搜索

        $where = function($query) use ($request){

            if($request->type){
                $query->where('cate',$request->type);
            }
            if($request->cate){ //饰品分类
                $query->where('type_id',$request->cate);
            }

            if($request->keywords){
                $query->where(function ($query) use ($request){
                    $query->Where('name', 'like', '%'.$request->keywords.'%')->orWhere('No', 'like', '%'.$request->keywords.'%');
                });

            }

            $query->where('status',1);
        };


        $goods_list = Good::with(["color:id,color","material:id,material"])
            ->where($where)
//            ->when($keywords,function($query) use ($keywords){
//                $query->where(function ($query) use ($keywords){
//                    return $query->whereHas('user', function ($query) use ($keywords) {
//                        return $query->where('mobile', 'like', '%'.$keywords.'%');
//                    })->orWhereHas('activity',function ($query) use ($keywords){
//                        return $query->Where('title', 'like', '%'.$keywords.'%');
//                    });
//                });
//
//            })
            ->select(['id','color_id','material_id','name','img','old_price','No','new_price','stock'])->paginate($request->pageSize?:20);//获取商品列表

        foreach ($goods_list as $k=>$v){

            $goods_list[$k]->thumb_img =$v->img[0];
            if($v->material){
                $goods_list[$k]->str = $v->color->color."-". $v->material->material;
            }else{
                $goods_list[$k]->str = "";
            }


        }


        return $this->success($goods_list);

    }

    //获取商品详情
    public function getGoodsInfo(Request $request){
        $id = $request->goods_id;

        $info = DB::table('goods')->find($id);


        return $this->success($info);

    }



    public function addOrder(Request $request){

        $goods = $request->goods; //商品信息
        $nums = $request->nums; //商品数量

        $order_note = $request->order_note;

        $type = $request->type; //订单类型 1开蚌 2饰品
        if(empty($goods) || empty($nums))
            return $this->failed('参数不全');
        $good_num = array_combine($goods,$nums);
        $user = Auth::guard('api')->user();

        $goodsInfo = DB::table('goods')->whereIn('id',$goods)->get();

        $total_money = 0;

        foreach ($goodsInfo as $k=>$v){

            if($v->stock < $good_num[$v->id]){
                return $this->failed($v->name.'库存不够');
            }
            $total_money += $v->new_price*$good_num[$v->id];

            $type = $v->cate;
        }

        DB::beginTransaction();
        $order = new Order();

        $order->user_id = $user->id;
        $order->order_sn = $this->getOrderSn();
        $order->money = $total_money;
        $type && $order->type = $type;
        $order_note && $order->order_note = $order_note;
        $res1 = $order->save();

        $data = [];

        foreach ($goodsInfo as $k=>$v){

            $data[$k]['order_id'] = $order->id;
            $data[$k]['goods_id'] = $v->id;
            $data[$k]['goods_name'] = $v->name;
            $data[$k]['goods_img'] = explode(',',$v->img)[0];
            $data[$k]['goods_price'] = $v->new_price;
            $data[$k]['num'] = $good_num[$v->id];
            $data[$k]['total_money'] = $v->new_price*$good_num[$v->id];
            $data[$k]['created_at'] = date("Y-m-d H:i:s");
            $data[$k]['updated_at'] = date("Y-m-d H:i:s");

        }
        $res2 = OrderGood::insert($data);

        if($res1 && $res2){
            DB::commit();

            $pay = new WechatPayController();
            return $pay->prepayOrder($order->id,$user['openid']);

        }else{
            DB::rollBack();
            return $this->failed("订单生成失败");
        }

    }


    public function addOrder1(Request $request){

        $goods = $request->goods; //商品信息
        $nums = $request->nums; //商品数量

        $order_note = $request->order_note;
        $note_img = $request->note_img;

        $type = $request->type; //订单类型 1开蚌 2饰品
        if(empty($goods) || empty($nums))
            return $this->failed('参数不全');
        $good_num = array_combine($goods,$nums);
        $user = Auth::guard('api')->user();

        $goodsInfo = DB::table('goods')->whereIn('id',$goods)->get();

        $total_money = 0;

        foreach ($goodsInfo as $k=>$v){

            if($v->stock < $good_num[$v->id]){
                return $this->failed($v->name.'库存不够');
            }
            $total_money += $v->new_price*$good_num[$v->id];

            $type = $v->cate;
        }

        DB::beginTransaction();
        $order = new Order();

        $order->user_id = $user->id;
        $order->order_sn = $this->getOrderSn();
        $order->money = $total_money;
        $type && $order->type = $type;
        $order_note && $order->order_note  = $order_note;
        $note_img && $order->note_img  = $note_img;
        $res1 = $order->save();

        $data = [];

        foreach ($goodsInfo as $k=>$v){

            $data[$k]['order_id'] = $order->id;
            $data[$k]['goods_id'] = $v->id;
            $data[$k]['goods_name'] = $v->name;
            $data[$k]['goods_img'] = explode(',',$v->img)[0];
            $data[$k]['goods_price'] = $v->new_price;
            $data[$k]['num'] = $good_num[$v->id];
            $data[$k]['total_money'] = $v->new_price*$good_num[$v->id];
            $data[$k]['created_at'] = date("Y-m-d H:i:s");
            $data[$k]['updated_at'] = date("Y-m-d H:i:s");

        }
        $res2 = OrderGood::insert($data);

        if($res1 && $res2){
            DB::commit();
            return $this->success(["order_id"=>$order->id]);


        }else{
            DB::rollBack();
            return $this->failed("订单生成失败");
        }

    }

    public function PayOrder(Request $request){

        $id = $request->order_id;


        $order = Order::with("goods:order_id,goods_name,goods_id,goods_price,num,total_money")->find($id);

        $user = Auth::guard('api')->user();

        if(!$order)
            return $this->failed("订单信息不存在");
        if($order->pay_status==1)
            return $this->failed("订单已支付");

        foreach ($order->goods as $k=>$v){
            $good = Good::find($v['goods_id']);
            if($good->stock < $v['num']){
                return $this->failed($v->name.'库存不够');
            }

        }


        $pay = new WechatPayController();

        return $pay->prepayOrder($order->id,$user['openid']);

    }






    public function getOrderSn(){

        $rand = mt_rand(10000, 99999);

        return date('YmdHis', time()) . $rand;

    }


    //获取订单详情接口
    public function getOrderDetail(Request $request){
        $order_id = $request->order_id;

        $order = Order::with("goods:order_id,goods_name,goods_id,goods_img,goods_price,num,total_money")
            ->select(['id','order_sn','money','old_money','check_status','order_status','pay_status','type','check_time','created_at','order_note','note_img'])->find($order_id);


        foreach ($order->goods as $k=>$v){

            $goods =  Good::with(["color:id,color","material:id,material"])
                ->where('id',$v['goods_id'])->select(['id','color_id','material_id','No',])->first();
            $order->goods[$k]->color = $goods->color->color;
            $order->goods[$k]->No = $goods->No;
            if($goods->material){
                $order->goods[$k]->str = $goods->color->color.'-'.$goods->material->material;
            }

        }



        return $this->success($order);

    }

    //订单列表
    public function getorderList(Request $request){
        //全部 待支付 待核销 待付款 已完成
        $user = Auth::guard('api')->user();

        $where = function($query) use ($request){
            if($request->order_status || $request->order_status===0 || $request->order_status==='0'){
                $query->where('order_status',$request->order_status);
            }

        };

        $order_list = Order::with("goods:goods_id,order_id,goods_name,goods_price,num")
            ->select(['id','money','check_status','pay_status','order_status','order_sn','created_at'])
            ->where($where)
            ->where('user_id',$user->id)->orderByDesc('id')->get();

        foreach ($order_list as $k=>$v) {


            $data = $v->id.','.time();

            $order_list[$k]['data'] = base64_encode($data);

            foreach ($v->goods as $kk=>$vv){
                $goods =  Good::with(["color:id,color","material:id,material"])
                    ->where('id',$vv['goods_id'])->select(['id','color_id','img','material_id','No',])->first();

              if($goods && $goods->material){
                    $order_list[$k]->goods[$kk]->str = $goods->color->color.'-'.$goods->material->material;
                    $order_list[$k]->goods[$kk]->goods_img =  $goods->img[0];
                }
            }

        }


        return $this->success($order_list);
    }

    //订单列表1
    public function getorderList1(Request $request){
        //全部 待支付 待核销 待付款 已完成
        $user = Auth::guard('api')->user();

        $where = function($query) use ($request){
            if($request->order_status || $request->order_status===0 || $request->order_status==='0'){
                $query->where('order_status',$request->order_status);
            }

        };

        $order_list = Order::with("goods:goods_id,order_id,goods_name,goods_price,num")
            ->select(['id','money','check_status','pay_status','order_status','order_sn','created_at'])
            ->where($where)
            ->where('user_id',$user->id)->orderByDesc('id')->paginate($request->pageSize?:10);

        foreach ($order_list as $k=>$v) {


            $data = $v->id.','.time();

            $order_list[$k]['data'] = base64_encode($data);

            foreach ($v->goods as $kk=>$vv){
                $goods =  Good::with(["color:id,color","material:id,material"])
                    ->where('id',$vv['goods_id'])->select(['id','color_id','img','material_id','No',])->first();

                if($goods && $goods->material){
                    $order_list[$k]->goods[$kk]->str = $goods->color->color.'-'.$goods->material->material;
                    $order_list[$k]->goods[$kk]->goods_img =  $goods->img[0];
                }
            }

        }


        return $this->success($order_list);
    }

    //商品价格是否显示
    public function isShow(){

        $is_show = DB::table('config')->where('name','is_show')->value('value');

        return $this->success($is_show);

    }



    //轮播图
    public function getAd(Request $request){
        $list = DB::table('ad')->where('status',1)->get();

        return $this->success($list);
    }


    //关于我们
    public function getArticle(Request $request){
        $type = $request->type?:1;

        if($type == 3){
            return $this->success(['mobile'=>'15921050479']);
        }

        return $this->success(DB::table('article')->where('type',$type)->first());
    }


    public function deliverly(Request $request){

        $order_id = $request->order_id;
        $order = Order::find($order_id);

        $shipping = new ShippingController();

        $res = $shipping->sendDelivery($order->toArray());

        return $this->success($res);

    }


    public function appVersion(){

        $info  = AppVersion::orderByDesc('id')->first();

        return $this->success($info);
    }


}
